package aize.corp.freeconso;

import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.zip.GZIPInputStream;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;

import sock.HttpClientFlo;

import aize.corp.freeconso.R;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import database.DBAdapter;

public class Factures extends Activity {

	private HttpContext mHttpContext = new BasicHttpContext();
	private CookieStore mCookieStore = new BasicCookieStore();
	private DBAdapter database = new DBAdapter(this);
	private HttpClient client = new HttpClientFlo(this);
	private ArrayList<String> factures = new ArrayList<String>();
	private ArrayList<String> facturesCost = new ArrayList<String>();
	private String currentData = null;
	private String login = null;

	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.factures);
        
    	database.open();
    	if(database.countSetting() == 0) {
    		Toast.makeText(getApplicationContext(), "Merci de configurer vos identifiants !", Toast.LENGTH_SHORT).show();
    		database.close();
    		finish();  
    	}
    	else {            
    		database.close();
            TextView texteView = (TextView) findViewById(R.id.textViewTitle);
            Typeface font = Typeface.createFromAsset(getAssets(), "ariblk.ttf");
            texteView.setTypeface(font);   
            
            factures = getIntent().getStringArrayListExtra("aize.eu.freeconso.list");
            facturesCost = getIntent().getStringArrayListExtra("aize.eu.freeconso.listcost");
            
            login = getIntent().getStringExtra("aize.eu.freeconso.login");
            
            BasicClientCookie cook1 = new BasicClientCookie(getIntent().getStringExtra("aize.eu.freeconso.cook1name"), getIntent().getStringExtra("aize.eu.freeconso.cook1value"));
            BasicClientCookie cook2 = new BasicClientCookie(getIntent().getStringExtra("aize.eu.freeconso.cook2name"), getIntent().getStringExtra("aize.eu.freeconso.cook2value"));
            BasicClientCookie cook3 = new BasicClientCookie(getIntent().getStringExtra("aize.eu.freeconso.cook3name"), getIntent().getStringExtra("aize.eu.freeconso.cook3value"));
            
            cook1.setDomain("mobile.free.fr");
            cook2.setDomain("mobile.free.fr");
            cook3.setDomain("mobile.free.fr");
            
            mCookieStore.addCookie(cook1);
            mCookieStore.addCookie(cook2);
            mCookieStore.addCookie(cook3);
            mHttpContext.setAttribute(ClientContext.COOKIE_STORE, mCookieStore);
            
            updateDisplay();
    	}
    }
    
	private String getFacture(int num) {
		HttpGet get = new HttpGet("https://mobile.free.fr/moncompte/ajax.php?page=facture&type=html&mode=popup&1="+login+"&date="+factures.get(num));
		get.addHeader("Referer", "https://mobile.free.fr/moncompte/index.php?page=suiviconso");
		get.addHeader("Accept-Encoding", "gzip, deflate");
		
		try {
			HttpResponse getResponsedata = client.execute(get, mHttpContext);

			Header contentEncoding = getResponsedata.getFirstHeader("Content-Encoding");
			BufferedReader in1 = null;
			if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip"))
				in1 = new BufferedReader(new InputStreamReader(new GZIPInputStream(getResponsedata.getEntity().getContent())));
			else
				in1 = new BufferedReader(new InputStreamReader(getResponsedata.getEntity().getContent()));
			
			StringBuffer sb = new StringBuffer();
			String line;
			
			while ((line = in1.readLine()) != null) {
				sb.append(line+"\n");
				if(line.contains("</html>"))
					break;
			}
			getResponsedata.getEntity().consumeContent();
			return sb.toString();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	private void updateDisplay() {
		ArrayList<HashMap<String, String>> listItem = new ArrayList<HashMap<String, String>>();

		boolean listener = true;
		if(factures.size()==0) {
			factures.add("Pas de facture !");
			listener = false;
			HashMap<String, String> map = new HashMap<String, String>();
			map.put("tel","Pas de facture !");
			map.put("img", String.valueOf(R.drawable.facture));
			listItem.add(map);
		}
		else {	
			for(int i=0;i<factures.size();i++) {
				HashMap<String, String> map = new HashMap<String, String>();
				map.put("tel","Facture du "+factures.get(i).substring(6, 8)+"-"+factures.get(i).substring(4, 6)+"-"+factures.get(i).substring(0, 4));
				map.put("cost",facturesCost.get(i));
				map.put("img", String.valueOf(R.drawable.facture));
		        listItem.add(map);
			}
		}
		
		SimpleAdapter adapter = new SimpleAdapter(getApplicationContext(), listItem, R.layout.list_item_facture,
	               new String[] {"img", "tel", "cost"}, new int[] {R.id.img, R.id.tel, R.id.cost});
		
		ListView itemlist = (ListView) findViewById(R.id.itemlist);
		int index = itemlist.getFirstVisiblePosition();
		int top = (itemlist.getChildAt(0) == null) ? 0 : itemlist.getChildAt(0).getTop();

		itemlist.setAdapter(adapter);
		itemlist.setSelectionFromTop(index, top);
		if(listener) {
			itemlist.setOnItemClickListener(new OnItemClickListener(){
	
				public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
					openContextMenu(arg1);
				}});
		}
		registerForContextMenu(itemlist);
	}
	
    private Runnable webThread = new Runnable(){
		public void run() {
			Intent intent = new Intent(Factures.this, FactureWeb.class);
			Bundle b = new Bundle();
			b.putString("aize.eu.freeconso.datafact", currentData);
			
			intent.putExtras(b);
			startActivity(intent);
	  }
    };
    
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		menu.add(0, 1, 0, "Voir");
		menu.add(0, 2, 0, "Envoyer");
	}

	public boolean onContextItemSelected(MenuItem item) {
	AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
		switch (item.getItemId()) {
			case 1:
				showFacture(info.position);
				return true;
			case 2:
				sendFacture(info.position);
				return true;
			default:
				return super.onContextItemSelected(item);
		}
	}
	
    public void WriteGlobalAuto(String data){ 
    	try {
    		String txt = "<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'/>";
    		FileOutputStream fos = new FileOutputStream(Environment.getExternalStorageDirectory().getAbsolutePath() + "/facture.html");
    		 
    		Writer out = new OutputStreamWriter(fos, "UTF-8");
    		txt += data;
    		out.write(txt);
    		out.flush();
    		out.close();
    		 
    		} catch (Throwable t) {
    			Toast.makeText(this, "Request failed: " + t.toString(),
    			Toast.LENGTH_LONG).show();
    		}
    }
    
	private void sendFacture(int position) {
		currentData = getFacture(position);	
		WriteGlobalAuto(currentData);
    	final Intent MessIntent = new Intent(Intent.ACTION_SEND); 
    	MessIntent.setType("plain/text");
    	MessIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    	MessIntent.putExtra(Intent.EXTRA_SUBJECT, "Facture FreeMobile du "+factures.get(position).substring(6, 8)+"-"+factures.get(position).substring(4, 6)+"-"+factures.get(position).substring(0, 4));
    	MessIntent.putExtra(Intent.EXTRA_TEXT, "Votre facture");
    	MessIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + Environment.getExternalStorageDirectory().getAbsolutePath() + "/facture.html"));
    	startActivity(Intent.createChooser(MessIntent, "Envoyer avec..."));
    	
	}

	private void showFacture(int position) {
		currentData = getFacture(position);
		new Thread(webThread).start();
	}
}